package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetmealService;


import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.jxls.common.Context;
import org.jxls.transform.poi.PoiContext;
import org.jxls.util.JxlsHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 展示会员数量折线图
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){

        //组装过去12个月的数据, 前端是一个数组
        List<String> mouths = new ArrayList<>(12);

        //获取日历对象
        Calendar calendar = Calendar.getInstance();

        //获取过去一年
        calendar.add(Calendar.YEAR,-1);

        //将日期进行格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        //将日历进行遍历
        for (int i = 0; i < 12; i++) {

            //每遍历一次，就加1
            calendar.add(Calendar.MONTH,1);

            //过去的日期, 设置好的日期
            Date date = calendar.getTime();

            //将月份进行格式化
            String mouth = sdf.format(date);

            //添加,在前端只展示年-月
            mouths.add(mouth);
        }
        //调用服务查询过去12个月会员数据
       List<Integer>  memberCount = memberService.getMemberReport(mouths);

        //把查到的数据封装进map
        HashMap<String, Object> result = new HashMap<String, Object>();

        //将月份数据放进map中
        result.put("months",mouths);

        //将每月会员人数放进map中
        result.put("memberCount",memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,result);
    }

    /**
     * 显示套餐预约占比饼图
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){

        // 调用服务查询套餐数量
       List<Map<String, Object>> setmealCount = setmealService.getSetmealReport();

        //获取套餐的名称
        List<String> setmealNames = setmealCount.stream().map(map->{return (String)map.get("name");

        }).collect(Collectors.toList());

        //封装返回的结果
        HashMap<String, Object> result = new HashMap<String, Object>();

        //将套餐数量放进map中
        result.put("setmealCount",setmealCount);

        //将套餐名称放进map中
        result.put("setmealNames",setmealNames);

        //返回数据给前端
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,result);
    }

    /**
     * 运营数据统计
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){

        Map<String, Object> reportData = reportService.getBusinessReportData();

        //返回数据给前端
        return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,reportData);
    }

    /**
     * 导出运营统计数据报表
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
       //查询报表数据
        Map<String, Object> reportData = reportService.getBusinessReportData();

        //获取模板所在
        String template = request.getSession().getServletContext().getRealPath("/template/report_template.xlsx");

       //创建Workbook传模板所在路径
        try {
            Workbook wk = new XSSFWorkbook(template);

            //获取工作表
            Sheet sht = wk.getSheetAt(0);

            //获取行，单元格，设置相应的数据,通过模板填充数据
            sht.getRow(2).getCell(5).setCellValue(((String) reportData.get("reportDate")));

            //会员数量
            sht.getRow(4).getCell(5).setCellValue(((String) reportData.get("todayNewMember")));
            sht.getRow(4).getCell(5).setCellValue(((String) reportData.get("totalMember")));
            sht.getRow(5).getCell(5).setCellValue(((String) reportData.get("thisWeekNewMember")));
            sht.getRow(5).getCell(7).setCellValue(((String) reportData.get("thisMonthNewMember")));

            //预约到诊
            sht.getRow(7).getCell(5).setCellValue(((String) reportData.get("todayOrderNumber")));
            sht.getRow(7).getCell(7).setCellValue(((String) reportData.get("todayVisitsNumber")));
            sht.getRow(8).getCell(5).setCellValue(((String) reportData.get("thisWeekOrderNumber")));
            sht.getRow(8).getCell(7).setCellValue(((String) reportData.get("thisWeekVisitsNumber")));
            sht.getRow(9).getCell(5).setCellValue(((String) reportData.get("thisMonthOrderNumber")));
            sht.getRow(9).getCell(7).setCellValue(((String) reportData.get("thisMonthVisitsNumber")));

            //热门套餐，遍历输出填值
            List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");

            int rowIndex = 12;

            for (Map map : hotSetmeal) {

                Row row = sht.getRow(rowIndex);

                row.getCell(4).setCellValue((String) map.get("name"));

                row.getCell(5).setCellValue((Long) map.get("setmeal_count"));

                //热门套餐占比为小数，所以要转换为bigDecimal
                BigDecimal bigDecimal = (BigDecimal) map.get("proportion");

                row.getCell(6).setCellValue(bigDecimal.doubleValue());

                row.getCell(7).setCellValue((String) map.get("remark"));

                rowIndex++;
            }
            //内容体设置, 告诉浏览器的，下载的文件是就excel的文档
            response.setContentType("application/vnd.ms-excel");

            String filename = "运营数据统计.xlsx";

            //原始数据字节流,ISO-8859-1
            byte[] bytes = filename.getBytes();

            filename = new String(bytes,"ISO-8859-1");

            // 响应头信息设置
            response.setHeader("Content-Disposition","attachment;filename="+filename);

            // 写到输出流
            wk.write(response.getOutputStream());

            wk.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 导出运营统计数据excel报表
     * @param request
     * @param response
     */
    @GetMapping("/exportBusinessReport2")
    public void exportBusinessReport2(HttpServletRequest request,HttpServletResponse response){

        // 查询报表数据
        Map<String, Object> reportData = reportService.getBusinessReportData();

        // 获取模板文件
        String template = request.getSession().getServletContext().getRealPath("/template/report_template2.xlsx");

        // 创建工作簿，读取模板，数据模型
        Context context = new PoiContext();

        context.putVar("obj",reportData);

        try {
        response.setContentType("application/vnd.ms-excel");

        //设置响应头
        response.setHeader("Content-Disposition","attachment;filename=report.xlsx");

            //把数据模型中的数据填充到文件中
            JxlsHelper.getInstance().processTemplate(new FileInputStream(template),response.getOutputStream(),context);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
